﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using DriveBeamEditor.Properties;
using GBlastImaging;

namespace DriveBeamEditor.Forms
{
    public partial class SplashForm : Form
    {
        #region Properties

        /// <summary>Gets or sets the idle time before closing</summary>
        public int IdleTime { get; set; }

        #endregion

        #region CTORs

        public SplashForm()
        {
            InitializeComponent();
            SetStyle(
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.DoubleBuffer |
                ControlStyles.OptimizedDoubleBuffer |
                ControlStyles.ResizeRedraw |
                ControlStyles.SupportsTransparentBackColor |
                ControlStyles.UserPaint,
                true
            );
            InitializeRegion();
        }

        #endregion

        #region Methods

        private void InitializeRegion()
        {
            Region = GBIDrawings.GetRegion(Resources.TitleBar, Color.FromArgb(0, 0, 0, 0));
        }

        private void FadeIn()
        {
            for (var i = 0f; Opacity < 1; i += 0.01f)
            {
                Opacity = i;
                Application.DoEvents();
                Thread.Sleep(10);
            }
        }

        private void FadeOut()
        {
            for (var i = 1f; Opacity > 0; i -= 0.01f)
            {
                Opacity = i;
                Application.DoEvents();
                Thread.Sleep(10);
            }
        }

        private void Temporize()
        {
            for (var i = 0; i < IdleTime; i++)
            {
                Application.DoEvents();
                Thread.Sleep(0);
            }
        }

        #endregion

        #region Events

        protected override void OnShown(EventArgs e)
        {
            Opacity = 0;
            base.OnShown(e);
            FadeIn();
            Temporize();
            Close();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            FadeOut();
            base.OnClosing(e);
        }

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 0x84:
                    base.WndProc(ref m);
                    if ((int) m.Result == 0x1)
                        m.Result = (IntPtr)0x2;
                    return;
            }

            base.WndProc(ref m);
        }

        #endregion
    }
}
